//-----------------------------------------------------------------------
// <copyright file="SpecifiedPublicationSelectorPolicy.cs" company="iron9light">
//      Copyright (c) iron9light. All rights reserved.
// </copyright>
// <author>iron9light</author>
//-----------------------------------------------------------------------

namespace EventBrokerExtension
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    using Microsoft.Practices.ObjectBuilder2;
    using Microsoft.Practices.Unity.Utility;

    /// <summary>
    /// An implemnetation of <see cref="IPublicationSelectorPolicy"/> which returns
    /// the set of specific publication that the selector was configured with.
    /// </summary>
    public class SpecifiedPublicationSelectorPolicy : IPublicationSelectorPolicy
    {
        private readonly List<PublicationInfo> publicationInfos = new List<PublicationInfo>();

        public void Add(EventInfo eventInfo, string eventTopic)
        {
            this.publicationInfos.Add(new PublicationInfo(eventTopic, eventInfo));
        }

        public IEnumerable<PublicationInfo> GetPublicationInfos(IBuilderContext context)
        {
            Type typeToBuild = BuildKey.GetType(context.BuildKey);
            ReflectionHelper currentTypeReflector = new ReflectionHelper(typeToBuild);
            foreach (PublicationInfo info in this.publicationInfos)
            {
                EventInfo eventInfo = info.TargetEvent;

                PublicationInfo publicationInfo;

                if (new ReflectionHelper(eventInfo.DeclaringType).IsOpenGeneric)
                {
                    eventInfo = currentTypeReflector.Type.GetEvent(eventInfo.Name);
                    publicationInfo = new PublicationInfo(info.EventTopic, eventInfo);
                }
                else
                {
                    publicationInfo = info;
                }

                yield return publicationInfo;
            }
        }
    }
}